package com.zdd.ehe.controller;

import com.zdd.ehe.result.Result;
import com.zdd.ehe.service.ISpiderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.python.util.PythonInterpreter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @title:
 * @author:
 * @description:
 * @createDate: 2023/3/18  21:33
 */
@Api(tags = "爬虫模块")
@RestController
@RequestMapping("/spider")
public class SpiderController {
    @Resource
    private ISpiderService spiderService;


    @ApiOperation("爬虫启动接口")
    @PostMapping("/getspider")
    public Result getPrice(@RequestParam("type") String type){
        if(!type.equals("price") && !type.equals("news") && !type.equals("pest")){
            return Result.error(4001,"类型错误");
        }
        String localPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath() + "/spider/";
        String[] fileNameList = {
                "price_Timing_task.py",
                "news_Timing_task.py"
        };


        String fileName = "";
        if(type.equals("price")) {
            fileName = fileNameList[0];
        }else if(type.equals("news")){
            fileName = fileNameList[1];
        }

        String pathx = localPath + fileName;
        String path = "";

        // 去除多余字符
        for(int i = 1;i<pathx.length();i++){
            path += pathx.charAt(i);
        }

        Boolean flag = spiderService.executeAsyncTask(path);
        if(flag == Boolean.FALSE){
            return Result.error(4002,"爬虫启动失败");
        }

        return Result.success("爬虫已启动,数据更新中");
    }


}
